package com.system.colleges.controller;

import com.system.colleges.entity.CollegeMajors;
import com.system.colleges.entity.RecommendResult;
import com.system.colleges.entity.Result;
import com.system.colleges.entity.Users;
import com.system.colleges.entity.CollegeMajorWeight;
import com.system.colleges.service.CollegeMajorsService;
import com.system.colleges.service.CollegesService;
import com.system.colleges.service.MajorsService;
import com.system.colleges.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@ResponseBody
@CrossOrigin
@Slf4j
@RequestMapping("/users")
public class UsersController {

    @Autowired
    UsersService service;
    @Autowired
    CollegesService collegesService;
    @Autowired
    CollegeMajorsService collegeMajorsService;

    @Autowired
    MajorsService majorsService;

    @RequestMapping("/queryAll")
    public List<Users> queryAllUsers(){
        return service.queryAllUsers();
    }

    @GetMapping("/findByPage")
    public Map<String, Object> findByPage(Integer page, Integer rows){
        page = page==null?1:page;
        rows = rows==null?8:rows;
        HashMap<String,Object> map = new HashMap<>();
        List<Users> users;
        Integer totals ;
        int totalPage ;
        //分页处理
        users = service.findUsersByPage(page,rows);
        //计算总页数
        totals = service.queryAllUsers().size();
        totalPage = totals%rows == 0?totals/rows:totals/rows+1;
        map.put("users",users);
        map.put("totals",totals);
        map.put("totalPage",totalPage);
        map.put("page",page);
        return map;
    }

    @PostMapping("/register")
    public Result Register(@RequestBody Users users){
        Result result = new Result();
        System.out.println("接收到的User对象: "+users.toString());
        int rank = service.getRanks(users.getScore());
        users.setRanks(rank);
        try {
            service.Register(users);
            result.setMsg("注册成功!");
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage()).setState(false);
        }
        return result;
    }

    @GetMapping("/findUsersByName")
    public int findUsersByName(String name){
        return service.findUserByName(name);
    }

    @GetMapping("/findUsersByNameWhileReg")
    public int findUserByNameWhileReg(String name){
        return service.findUsersByNameWhileReg(name);
    }

    @RequestMapping("/login")
    public Result login(@RequestBody Users users, HttpServletRequest request/*, HttpSession session*/){
        Result r = new Result();
        System.out.println(users);
        Users u = service.login(users);
        if (u==null){
            log.info("用户名错误!");
            r.setState(false).setMsg("用户名错误");
        }else if (!Objects.equals(u.getPassword(), users.getPassword())){
            log.info("密码错误!");
            r.setState(false).setMsg("密码错误");
        }else {
            request.getServletContext().setAttribute(u.getId(), u);
            System.out.println(u.getId());
            r.setId(u.getId());
            r.setMsg("登陆成功");
        }
        return r;
    }

    @RequestMapping("/loginId")
    public Result loginById(@RequestBody Users users, HttpServletRequest request){
        Result r = new Result();
        Users u = service.loginById(users);
        if (u==null){
            log.info("用户名错误!");
            r.setState(false).setMsg("用户名错误");
        }else if (!Objects.equals(u.getPassword(), users.getPassword())){
            log.info("密码错误!");
            r.setState(false).setMsg("密码错误");
        }else {
            request.getServletContext().setAttribute(u.getId().toString(), u);
            System.out.println(u.getId().toString());
            r.setId(u.getId().toString());
            r.setMsg("登陆成功");
        }
        return r;
    }

    @PostMapping("/updateUsers")
    public Result updateUsers(@RequestBody Users users){
        Result result = new Result();
        System.out.println("接收到的User对象: "+users.toString());
        int rank = service.getRanks(users.getScore());
        users.setRanks(rank);
        try {
            service.updateUsers(users);
            result.setMsg("更新用户信息成功!");
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage()).setState(false);
        }
        return result;
    }

    @GetMapping("/getUsersById")
    public Users getUsersById(String id){
        return service.findUsersById(id);
    }

    @GetMapping("/getUsersRoleById")
    public int getUsersRoleById(String id){
        return service.getUsersRoleById(id);
    }

    @GetMapping("/getRecommend")
    public List<RecommendResult> getRecommend(String score, String type, String aimRegion, String aimMajor, String aimCollege){
//        System.out.println(score);
        int grade = Integer.parseInt(score)+20;
        List<CollegeMajors> cms = collegeMajorsService.queryAllCollegeMajors(grade);
        ArrayList<String> types = new ArrayList<>();    //types装的是这个用户的选课类型
        types.add(type.substring(0,2));
        types.add(type.substring(3,5));
        types.add(type.substring(6,8));
        for(int i = 0; i< cms.size(); i++){
            boolean isContain = true;
            String ty = cms.get(i).getType();           //tys里面装的是这个学校-专业的选科要求
            ArrayList<String> tys = new ArrayList<>();
            if(!ty.equals("不限")){
                if(ty.length()==2){
                    tys.add(ty);
                }else if(ty.length()==5){
                    tys.add(ty.substring(0,2));
                    tys.add(ty.substring(3,5));
                }else if(ty.length()==8){
                    tys.add(type.substring(0,2));
                    tys.add(type.substring(3,5));
                    tys.add(type.substring(6,8));
                }
            }
            for(int j=0;j<tys.size();j++){
                if (!types.contains(tys.get(j))) {
                    isContain = false;
                    break;
                }
            }
            if(!isContain){
                cms.remove(i);
                i--;
            }
        }
        ArrayList<CollegeMajorWeight> weights = new ArrayList<>();
        for(int i=0;i<cms.size();i++){
            weights.add(new CollegeMajorWeight(cms.get(i),500-Math.abs(grade-20-cms.get(i).getLowest())));
            if (aimRegion.contains(collegesService.queryCollegeById(cms.get(i).getCid()+"").getRegion())) {
                weights.get(i).weight = weights.get(i).weight+7;
            }
            if(majorsService.queryMajorByName(cms.get(i).getMname()) != null){
                if (aimMajor.contains((majorsService.queryMajorByName(cms.get(i).getMname()).getType()))) {
                    weights.get(i).weight = weights.get(i).weight+7;
                }
            }
            if(aimCollege.equals(collegesService.queryCollegeById(cms.get(i).getCid()+"").getName())){
                weights.get(i).weight = weights.get(i).weight+7;
            }
        }
        for(int i=0;i<weights.size()-1;i++){
            for(int j=0;j<weights.size()-i-1;j++){
                if(weights.get(j).getWeight()<weights.get(j+1).getWeight()){
                    CollegeMajorWeight temp =
                            new CollegeMajorWeight(weights.get(j).getCollegeMajors(),weights.get(j).getWeight());
                    weights.add(j+1,weights.get(j+1));
                    weights.remove(j);
                    weights.add(j+1,temp);
                    weights.remove(j+2);
                }
            }
        }
//        System.out.println(weights.size());
        List<RecommendResult> recommendResults = new ArrayList<>();
        for(int i=0;i<96;i++){
            recommendResults.add(new RecommendResult(weights.get(i).getCollegeMajors(),weights.get(i).getWeight(),
                    collegesService.queryCollegeById(weights.get(i).getCollegeMajors().getCid()+""),
                    collegeMajorsService.getRealType(weights.get(i).getCollegeMajors())) );
        }
//        System.out.println(cms);
        return recommendResults;
    }

    @GetMapping("/deleteUsers")
    public void deleteUsers(String id){
        service.deleteUsers(id);
    }

}
